package StudyCode.Component;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * @author lixiaoyao
 * @date 2018/11/22 0022、下午 1:00
 * @description 文件选择及显示窗体
 */
public class ImageViewerFrame extends JFrame {

	private static final int DEFAULT_WIDTH = 300;
	private static final int DEFAULT_HEIGHT = 400;
	private JLabel label;
	private JFileChooser chooser;

	public ImageViewerFrame() {
		setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

		// set up menu bar
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu menu = new JMenu("File");
		menuBar.add(menu);

		JMenuItem openItem = new JMenuItem("Open");
		menu.add(openItem);
		openItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				chooser.setCurrentDirectory(new File("."));

				// show file chooser dialog
				if (chooser.showOpenDialog(ImageViewerFrame.this) == JFileChooser.APPROVE_OPTION) {
					String name = chooser.getSelectedFile().getPath();
					label.setIcon(new ImageIcon(name));
					pack();
				}
			}
		});

		JMenuItem exiItem = new JMenuItem("Exit");
		menu.add(exiItem);
		exiItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		// use a label to display the images
		label = new JLabel();
		add(label);

		// set up file chooser
		chooser = new JFileChooser();

		// accept all image files ending with .jpg, .jpeg, .gif
		FileFilter fileFilter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif");
		this.chooser.setFileFilter(fileFilter);
		this.chooser.setAccessory(new ImagePreViewer(chooser));
		this.chooser.setFileView(new FileIconViewer(fileFilter, new ImageIcon("palette.gif")));
	}

	public static void main(String[] args) {
		ImageViewerFrame imageViewerFrame = new ImageViewerFrame();
		imageViewerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		imageViewerFrame.setVisible(true);
	}

}
